import 'package:family_expense/features/bank_card/models/bank.dart';
import 'package:family_expense/features/bank_card/models/bank_card.dart';
import 'package:family_expense/features/bank_card/services/bank_card_service.dart';
import 'package:family_expense/features/bank_card/services/bank_service.dart';
import 'package:family_expense/features/bank_card/widgets/bank_shared.dart';
import 'package:flutter/material.dart';
import 'package:my_flutter_core/my_flutter_core.dart';

class AddBankCard extends StatefulWidget {
  const AddBankCard({super.key});

  @override
  State<AddBankCard> createState() => _AddBankCardState();
}

class _AddBankCardState extends State<AddBankCard> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final BankService _bankService = BankService();
  final BankCardService _bankCardService = BankCardService();
  final BankCard _bankCard = BankCard(bank: Bank());

  List<Bank>? _banks;

  @override
  void initState() {
    super.initState();

    _queryAllWithBasicInfo();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('添加卡片')),
      body: _buildForm(),
    );
  }

  /// Builds the input form.
  Widget _buildForm() {
    // DO NOT PUT [Form] in [ListView]. Uses [SingleChildScrollView] instead.
    // Textfield in gallery gets reset if scrolled out of view.
    // https://github.com/flutter/flutter/issues/11500
    return Form(
      key: _formKey,
      child: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            SwitchListTile(
              title: const Text('信用卡'),
              value: _bankCard.isCreditCard!,
              onChanged: (value) {
                if (mounted) {
                  // Triggers build.
                  setState(
                    () => _bankCard.isCreditCard = !_bankCard.isCreditCard!,
                  );
                }
              },
            ),
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 10.0),
              child: SimpleDetailListTile(
                title: const Text('银行'),
                value: _bankCard.bank?.shortName != null
                    ? BankLogo(_bankCard.bank!)
                    : Container(),
                onTap: () => _showBankModalBottomSheet(),
              ),
            ),
            const Divider(),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16.0),
              child: TextFormField(
                keyboardType: TextInputType.text,
                decoration: const InputDecoration(
                  labelText: '卡名称',
                  hintText: '如龙卡、ETC、双币等',
                  prefixIcon: Icon(Icons.credit_card),
                ),
                validator: (value) => FormTextFieldValidator(
                  '卡名称',
                  value,
                  maxLength: BankCard.nameMaxLength,
                ).validate(),
                onSaved: (value) {
                  _bankCard.name = value;
                },
              ),
            ),
            _buildDivider(),
            AnimatedSize(
              duration: const Duration(milliseconds: 200),
              child: Visibility(
                visible: _bankCard.isCreditCard!,
                child: Column(
                  children: [
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 16.0),
                      child: TextFormField(
                        keyboardType: TextInputType.number,
                        decoration: const InputDecoration(
                          labelText: '账单日',
                          hintText: '如15是上月15号至本月14号的账单周期',
                          prefixIcon: Icon(Icons.date_range),
                        ),
                        validator: (value) {
                          String? result;

                          if (_bankCard.isCreditCard!) {
                            result = FormTextFieldValidator(
                              '账单日',
                              value,
                              isPositiveNumber: true,
                              maxLength: BankCard.statementDateMaxLength,
                            ).validate();
                          }

                          return result;
                        },
                        onSaved: (value) {
                          _bankCard.statementDate = value;
                        },
                      ),
                    ),
                    _buildDivider(),
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 16.0),
                      child: TextFormField(
                        keyboardType: TextInputType.number,
                        decoration: const InputDecoration(
                          labelText: '还款日',
                          hintText: '如24是当月24号。+3是下月3号。',
                          prefixIcon: Icon(Icons.date_range),
                        ),
                        validator: (value) {
                          String? result;

                          if (_bankCard.isCreditCard!) {
                            result = FormTextFieldValidator(
                              '还款日',
                              value,
                              isPositiveNumber: true,
                              maxLength: BankCard.paymentDueDateMaxLength,
                            ).validate();
                          }

                          return result;
                        },
                        onSaved: (value) {
                          _bankCard.paymentDueDate = value;
                        },
                      ),
                    ),
                    _buildDivider(),
                  ],
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16.0),
              child: TextFormField(
                keyboardType: TextInputType.text,
                decoration: const InputDecoration(
                  labelText: '客服号码',
                  hintText: '如400-xxx-xxxx、800-xxx-xxxx等。',
                  prefixIcon: Icon(Icons.phone),
                ),
                validator: (value) => FormTextFieldValidator(
                  '客服号码',
                  value,
                  isRequired: false,
                  maxLength: BankCard.customerServiceNumberMaxLength,
                ).validate(),
                onSaved: (value) {
                  _bankCard.customerServiceNumber = value;
                },
              ),
            ),
            _buildDivider(),
            Container(
              margin: const EdgeInsets.only(top: 40.0),
              height: 44.0,
              child: PressStatusButton(
                onPressed: _save,
                disabledChild: const Text(
                  '正在保存',
                  style: TextStyle(fontSize: 20.0),
                ),
                child: const Text('保 存', style: TextStyle(fontSize: 20.0)),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// Builds divider between list tile.
  Widget _buildDivider() {
    return const SizedBox(height: 20.0);
  }

  Future<void> _queryAllWithBasicInfo() async {
    final res = await _bankService.queryAllWithBasicInfo();

    if (mounted) {
      setState(() {
        _banks = res;
        _bankCard.bank = _banks?.first;
      });
    }
  }

  /// Shows a pick modal for bank selection.
  void _showBankModalBottomSheet() {
    BankShared.showBankModalBottomSheet(context, _banks!, (bank) {
      if (mounted) {
        // Triggers build.
        setState(() => _bankCard.bank = bank);
      }

      // Closes modal.
      NavigatorHelper.pop(context);
    }, bankCard: _bankCard);
  }

  /// Saves the new [BankCard] to server and pops.
  /// When pops notify previous page to reload.
  Future<void> _save() async {
    // Validate returns true if the form is valid, or false otherwise.
    if (!_formKey.currentState!.validate()) {
      showToast('请正确填写各项信息');
      return;
    }

    // Saves current form.
    _formKey.currentState!.save();

    // Saves the new bank card and pops if successful.
    final success = await _bankCardService.add(_bankCard);

    if (success && mounted) {
      // DO NOT use BuildContext across asynchronous gaps.
      // https://dart-lang.github.io/linter/lints/use_build_context_synchronously.html
      NavigatorHelper.pop(context, true);
    }
  }
}
